﻿using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SRB.Tg.Operate
{
    class PdfSharpTool
    {
        /// <summary>
        /// 合并PDF文件
        /// </summary>
        /// <param name="folderPath"></param>
        public void CombinePdfFiles(string folderPath)
        {
            try
            {
                //读取文件夹中的文件夹
                int fileCount = 0;
                int pageCount = 0;
                PdfDocument outPdfFile = new PdfDocument();
                List<string> fileNameList = new List<string>();
                List<string> fileError = new List<string>();
                foreach (var filename in Directory.GetFiles(folderPath))
                {
                    if (Path.GetExtension(filename) == ".pdf")
                    {
                        try
                        {
                            PdfDocument pdfFile = PdfReader.Open(filename, PdfDocumentOpenMode.Import);
                            fileCount++;
                            pageCount += pdfFile.PageCount;
                            foreach (var pdfPage in pdfFile.Pages)
                            {
                                outPdfFile.AddPage(pdfPage);
                                fileNameList.Add(string.Format("{0} {1}", Path.GetFileName(filename), pdfFile.PageCount));
                            }
                        }
                        catch (Exception ex)
                        {
                            fileError.Add(Path.GetFileName(filename));
                        }
                    }
                }
                string combineResult = "";
                if (fileCount > 0)
                {
                    //导出pdf文件
                    string timeTag = DateTime.Now.ToString("MMdd_HH_mm_ss");
                    SavePdfFile(folderPath + "\\合并", timeTag + ".pdf", outPdfFile);
                    fileNameList.Add(string.Format("共 {0} 个文件，共 {1} 页。", outPdfFile, pageCount));
                    if (fileError.Count > 0)
                    {
                        fileNameList.Add("合并失败文件：");
                        foreach (string p in fileError)
                        {
                            fileNameList.Add(p);
                        }
                    }
                    SaveTxtFile(folderPath + "\\合并", timeTag + ".txt", fileNameList);
                }
                combineResult = string.Format("合并文件数量：{0}", fileCount);
                if (fileError.Count > 0)
                {
                    combineResult += "\r\n";
                    combineResult += string.Format("合并失败文件数量：{0}", fileError.Count);
                }               
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        private void SavePdfFile(string folderPath, string fileName, PdfDocument pdfFile)
        {
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            pdfFile.Save(folderPath + "\\" + fileName);
        }
        private void SaveTxtFile(string folderPath, string fileName, List<string> content)
        {
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            string fileFullPath = folderPath + "\\" + fileName;
            if (!File.Exists(fileFullPath))
            {
                var newFile = File.CreateText(fileFullPath);
                newFile.Close();
            }
            using (StreamWriter sw = new StreamWriter(fileFullPath, true))
            {
                foreach (string line in content)
                {
                    sw.WriteLine(line);
                }
                sw.Close();
            }
        }

        /// <summary>
        /// 拆分PDF文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private static List<Stream> SplitPdf(string fileName)
        {
            // Open the file
            var inputDocument = PdfSharp.Pdf.IO.PdfReader.Open(fileName, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Import);
            var streamList = new List<Stream>();
            for (int idx = 0; idx < inputDocument.PageCount; idx++)
            {
                // Create new document
                var outputDocument = new PdfSharp.Pdf.PdfDocument
                {
                    Version = inputDocument.Version
                };
                outputDocument.Info.Title = String.Format("Page {0} of {1}", idx + 1, inputDocument.Info.Title);
                outputDocument.Info.Creator = inputDocument.Info.Creator;

                // Add the page and save it
                outputDocument.AddPage(inputDocument.Pages[idx]);
                var ms = new MemoryStream();
                outputDocument.Save(ms);
                streamList.Add(ms);
            }
            return streamList;
        }
    }

}
